package Controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import DAO.*;

import Model.EmployeeBean;
import Model.LeaveBean;
import Model.RankBean;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LeaveApplicationFormController
 */
@WebServlet("/LAFController")
public class LeaveApplicationFormController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LeaveApplicationFormController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession(true);
		session.setAttribute("error",null);
		int userid=1;// it will get later from the session attribute
		EmployeeDAO myEmployeeDao=DAOFactory.getInstance().getEmployeeDAO();// calling method from FactoryImpl
		RankDAO myRankDao=DAOFactory.getInstance().getRankDAO();
		EmployeeBean empBean = null;
		try {
			empBean = myEmployeeDao.findEmployeeById(userid);
			RankBean myRank=new RankBean();
			myRank=myRankDao.findByRankID(empBean.getRankID());
			empBean.setRankName(myRank.getRank_name());
			
		} catch (ClassNotFoundException e) {
			
			e.printStackTrace();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		session.setAttribute("myEmployeeBean",empBean);
		RequestDispatcher rd=request.getRequestDispatcher("/LeaveApplicationForm.jsp");
		rd.forward(request,response);
		
		
		
		
		
		
		
		
	
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		
		int empID=1; //later will get from session variable
		HttpSession session =request.getSession(false);
		session.setAttribute("error", " ");
		String error=null;
		RankDAO myRankDao=DAOFactory.getInstance().getRankDAO();
		LeaveDAO myLeaveDao=DAOFactory.getInstance().getLeaveDAO();
		OTClaimDAO otClaimDao=DAOFactory.getInstance().getClaimDAO();
		int  leaveType=Integer.parseInt(request.getParameter("leaveType"));
		System.out.println("*********YourLeaveType is ********"+leaveType);
		String fromDate=request.getParameter("fromDate");
		String toDate=request.getParameter("toDate");
		String reason=request.getParameter("reason");
		String workDs=request.getParameter("workDs");
		String contactD=request.getParameter("contactD");
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
		EmployeeBean currentEmp=(EmployeeBean) session.getAttribute("myEmployeeBean");
		DateCalculator dc=new DateCalculator();
		int takenLeaveDays=0;
		int allowedLeaveDays=0;
		String forwardTo=null;
		Date leaveStart = null;
		Date leaveEnd = null;
		long appliedLeaveDays = 0;
		try {
			appliedLeaveDays = dc.countTotalDays(fromDate,toDate);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} //
		try {
			leaveStart = sdf.parse(fromDate);
			leaveEnd=sdf.parse(toDate);
		} catch (ParseException e1) {
			
			e1.printStackTrace();
		}
	
		Date now = new java.util.Date();   
		
	
		 String createdate=sdf.format(now).toString();
		
	
		RankBean myRank = null;
		
		
		try {
			if(leaveType == 2)
			{
				System.out.println("====I m going to get Availble Days for type 2=========");
				allowedLeaveDays=otClaimDao.getAvailableDays(empID);//getAvaliable
				takenLeaveDays=0;
				
			}
			if(leaveType==1 || leaveType==3){
				myRank = myRankDao.findByRankID(currentEmp.getRankID());
				allowedLeaveDays=myRank.getTotal_days();
				takenLeaveDays=myLeaveDao.findTakenLeavesByEmpID(empID,leaveType);
				System.out.println("TOtal taken Leave Days----"+takenLeaveDays);
			}
		} catch (ClassNotFoundException e1) {
			
			e1.printStackTrace();
		} catch (SQLException e1) {
			
			e1.printStackTrace();
		} // get allwoed date based on employee rank
		
		
		
		
		if(leaveStart.before(now))
		{
			error="Now is before From date";
			forwardTo="LeaveApplicationForm.jsp";
	
		}
		else if(leaveEnd.before(leaveStart))
		{
			error="ToDate is before FromDate";
			forwardTo="LeaveApplicationForm.jsp";
		}
		if(appliedLeaveDays<14)
		{
			int weekendCounter=dc.weekendCounter(fromDate,toDate);
			appliedLeaveDays-=weekendCounter;
		}
		if((appliedLeaveDays+takenLeaveDays) >= allowedLeaveDays )
		{
			error="You don't have enough days to take leave";
			forwardTo="LeaveApplicationForm.jsp";
			
		}
		System.out.println("appliedLeaveDays=="+appliedLeaveDays);
		System.out.println("takenLeaveDays==="+takenLeaveDays);
		System.out.println("allowed Leave Days===="+allowedLeaveDays);

	System.out.println("ERROR is "+error);
		   
		if(error==null)
		{
		
	
		
		
	 
	  
			
			LeaveBean myLeave=new LeaveBean();
			myLeave.setLeavetype(leaveType);
			myLeave.setLeaveStartDate(fromDate);
			myLeave.setLeaveEndDate(toDate);
			myLeave.setLeaveReason(reason);
			myLeave.setWorkDissemination(workDs);
			myLeave.setContactDetails(contactD);
			myLeave.setEmployeeId(empID);
			myLeave.setCreatedDate(createdate);
			myLeave.setManagerComments(" ");
			myLeave.setModifiedDate(createdate);
			myLeave.setTotalDays(appliedLeaveDays);
		
			
			
			try {
				myLeaveDao.insertLeave(myLeave);
				forwardTo="/LeaveFormSuccessful.jsp";
			} catch (ClassNotFoundException e) {
				
				e.printStackTrace();
			} catch (DAOException e) {
				
				e.printStackTrace();
			} catch (SQLException e) {
			
				e.printStackTrace();
			} catch (Exception e) {
			
				e.printStackTrace();
			}  //saving data into the database
			
			   error=null;
		   }// end of else
		
		 session.setAttribute("error",error);
		 System.out.println("Before forwarding "+forwardTo);
		RequestDispatcher rd=request.getRequestDispatcher(forwardTo);
		rd.forward(request, response);
		
	}
	
	
	
}
